package cn.brilliantfuture.commentry.data.impl;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.jws.WebService;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.log4j.Logger;
import org.jboss.wsf.spi.annotation.WebContext;

import cn.brilliantfuture.commentry.data.DataMessageRemote;
import cn.brilliantfuture.commentry.data.DataMessageWebService;
import cn.brilliantfuture.commentry.entity.Lockers;
import cn.brilliantfuture.commentry.entity.OrderInformation;
import cn.brilliantfuture.commentry.entity.PickRecords;
import cn.brilliantfuture.commentry.entity.StorageGrid;
import cn.brilliantfuture.commentry.entity.StorageGridPurchaserNews;
import cn.brilliantfuture.commentry.entity.StorageGridSensor;
import cn.brilliantfuture.commentry.order.WorkflowMessageLocal;
import cn.brilliantfuture.commentry.util.DateTimeHelper;

/**
 * 
 * Title: Communication Entry
 * 
 * Author: LiTian
 * 
 * Date: 2011-11-2
 * 
 * Description: 上报数据类
 * 
 */
@Stateless
@WebService(endpointInterface = "cn.brilliantfuture.commentry.data.DataMessageWebService")
@WebContext(contextRoot = "/commentry", urlPattern = "/DataMessageWebService")
public class DataMessageImpl implements DataMessageRemote, DataMessageWebService {
	private static final Logger logger = Logger.getLogger(DataMessageImpl.class);
	
	private static final float DEFAULT_NON_DATA = 30100F;
	
	private static final float DEFAULT_WARM_TYPE = 2;
	
	private static final float DEFAULT_TEMP_TYPE = 3;
	
	@EJB WorkflowMessageLocal workflowMessageLocal;

	@PersistenceContext(unitName = "commentry-jpa")
	private EntityManager entityManager;

	@SuppressWarnings("unchecked")
	public void getData(String deviceSn, int gridCount, Date gatherDate, float[] tempValues, float[] humiVlues, short[] workStates) {
		logger.info("DataMessageImpl.getData(String deviceSn, int gridCount, Date gatherDate, float[] tempValues, float[] humiVlues)");
		List<StorageGrid> list = entityManager.createQuery("select distinct sg from StorageGrid sg inner join sg.lockers l where sg.deleted = 0 and l.device.deviceSn = :deviceSn group by sg.gridNum").setParameter("deviceSn", deviceSn).getResultList();
		//if (list.size() == gridCount) {
		if (list.size() < gridCount){
			gridCount = list.size();
		}
		
			for (int i = 0; i < gridCount; i++) {
				//过滤非数据
				if (DEFAULT_NON_DATA != tempValues[i]) {
					StorageGrid storageGrid = list.get(i);
					
					//判断配送仓时候否为恒温类型
					if(DEFAULT_TEMP_TYPE == storageGrid.getGridType() || DEFAULT_WARM_TYPE == storageGrid.getGridType()){
						storageGrid.setTemp(tempValues[i]);
						storageGrid.setHumi(humiVlues[i]);
						storageGrid.setWorkState(workStates[i]);
						StorageGridSensor sensor = new StorageGridSensor();
						sensor.setStorageGrid(storageGrid);
						sensor.setTemp(tempValues[i]);
						sensor.setHumi(humiVlues[i]);
						sensor.setWorkState(workStates[i]);
						sensor.setInsertTime(gatherDate);
						entityManager.persist(sensor);
						entityManager.merge(storageGrid);
					}
				}
			}
			entityManager.flush();
		//}

	}

	@SuppressWarnings("unchecked")
	public void getWorkStateData(String deviceSn, short tempControlState,
			short lockControlState, short keyboardState, short cardRederState,
			short barcodeGunState, short ledControlState, short gridCount, short[] hasGoods, short[] opends,
			short[] lockSatates, short[] tempStates) {
		List<StorageGrid> storageGrids = entityManager.createQuery("select sg from StorageGrid sg where sg.lockers.device.deviceSn = '" + deviceSn + "' order by sg.gridNum asc").getResultList();
		
		Date currentDate = new Date();
		
		if (null != storageGrids && storageGrids.size() > 0){
			Lockers lockers = storageGrids.get(0).getLockers();
			lockers.setBarcodeGunState(barcodeGunState == 1 ? true : false);
			lockers.setKeyboardState(keyboardState == 1 ? true : false);
			lockers.setLockBoardState(lockControlState == 1 ? true : false);
			lockers.setLedBoardState(ledControlState == 1 ? true : false);
			lockers.setReaderState(cardRederState == 1 ? true : false);
			lockers.setTempBoardState(tempControlState == 1 ? true : false);
			lockers.setPublishTime(currentDate);
			
			entityManager.merge(lockers);
			
			for (int i = 0; i < gridCount; i++) {
				StorageGrid storageGrid = storageGrids.get(i);
				
				if (storageGrid.isHasGoods() && hasGoods[i] == 0){
					logger.info("数据不一致");
					List<StorageGridPurchaserNews> sgpns = entityManager.createQuery("select sgpn from StorageGridPurchaserNews sgpn where sgpn.closing = 0 and sgpn.pick = 0 and sgpn.takeawayTime is null and sgpn.storageGrid.storageGridId = " + storageGrid.getStorageGridId() + " and sgpn.lockersId = " + storageGrid.getLockers().getLockersId()).getResultList();
					
					if (sgpns.size() > 0){
						StorageGridPurchaserNews sgpn = sgpns.get(0);
						sgpn.setClosing(1);
						sgpn.setPick(1);
						sgpn.setTakeawayTime(new Date());
						
						entityManager.merge(sgpn);
						
						PickRecords pickRecords = new PickRecords();		
						pickRecords.setCardNumber(sgpn.getPurchaser().getCardInfo().getCardNumber());
						pickRecords.setGridNum(storageGrid.getGridNum());
						pickRecords.setFlag(false);
						pickRecords.setOrderInformationNumber(sgpn.getOrderInformationNumber());
						pickRecords.setRfidSn(sgpn.getRfidSn());
						pickRecords.setInsertTime(DateTimeHelper.dateTimeToStr(currentDate, DateTimeHelper.DEFAULT_DATE_TIME_FORMAT));
						
						entityManager.persist(pickRecords);
						
						Object count = entityManager.createQuery("select count(pb) from ProductBatch pb where pb.deleted = 0 and pb.orderInformation.number = :number").setParameter("number", sgpn.getOrderInformationNumber()).getSingleResult();
						Object done = entityManager.createQuery("select count(sgpn) from StorageGridPurchaserNews sgpn where sgpn.refund = 0 and sgpn.pick = 1 and sgpn.orderInformationNumber = :number").setParameter("number", sgpn.getOrderInformationNumber()).getSingleResult();
						
						if (Integer.parseInt(count.toString()) == Integer.parseInt(done.toString())){
							entityManager.createQuery("update OrderInformation oi set oi.transactions = 7 where oi.number = :number").setParameter("number", sgpn.getOrderInformationNumber()).executeUpdate();
							List<OrderInformation> list = entityManager.createQuery("select oi from OrderInformation oi where oi.number = '" + sgpn.getOrderInformationNumber() + "'").getResultList();
							
							workflowMessageLocal.createWorkflowInfo(sgpn.getOrderInformationNumber(), 1, "会员完成取货...", new Date(), "系统", 4);
							
							if (null != list)
								if (list.size() > 0){
									Iterator<OrderInformation> it = list.get(0).getOrderInformations().iterator();
									
									while (it.hasNext()) {
										OrderInformation orderInformation = (OrderInformation) it.next();
										if (!orderInformation.isDeleted()){
											orderInformation.setTransactions(7);
											entityManager.merge(orderInformation);
										}
											
									}
									
								}
						}
					}
				}
				
				storageGrid.setHasGoods(hasGoods[i] == 1 ? true : false);
				storageGrid.setOpend(opends[i] == 1 ? true : false);
				storageGrid.setLockWorkState(lockSatates[i] == 1 ? true : false);
				storageGrid.setTempWorkState(tempStates[i] == 1 ? true : false);
				storageGrid.setPublishTime(currentDate);
				
				entityManager.merge(storageGrid);
			}
			
			entityManager.flush();
		}
	}

}
